package com.xiaoq.shop.repository.impl;

import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.shop.entity.SKUEntity;
import com.xiaoq.shop.repository.ISKURepository;
import com.xiaoq.vo.PagingVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.DeleteOptions;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenjh on 2017/11/3.
 */
@Repository
public class SKURepositoryImpl implements ISKURepository {

    @Autowired
    private Datastore dataStore;

    /**
     *  根据店Id 以及 规格 获取 票 SKU 列表
     * @param shopId
     * @param specificationNameList
     * @return
     */
    @Override
    public List<SKUEntity> getTicketSkuList(String shopId, List<String> specificationNameList, PagingVo pagingVo, Integer saleState) {
        if(StringUtils.isBlank(shopId) || CollectionUtils.isEmpty(specificationNameList)){
            return new ArrayList<>();
        }
        Query<SKUEntity> skuEntityQuery = dataStore.find(SKUEntity.class)
                .filter("shopId", shopId)
                .filter("specifications in", specificationNameList)
                .order("-sortIndex");
        if(saleState != null && !saleState.equals(ConstantUtil.SALE_STATE_ALL)){
            skuEntityQuery.filter("saleState", saleState);
        }
        if(pagingVo != null){
            skuEntityQuery.offset(pagingVo.getPageOffset()).limit(pagingVo.getPs());
        }
        return skuEntityQuery.asList();
    }

    @Override
    public long getTicketSkuListCount(String shopId, List<String> specificationNameList, PagingVo pagingVo, Integer saleStatus) {
        if(StringUtils.isBlank(shopId) || CollectionUtils.isEmpty(specificationNameList)){
            return 0L;
        }
        Query<SKUEntity> skuEntityQuery = dataStore.find(SKUEntity.class)
                .filter("shopId", shopId)
                .filter("specifications in", specificationNameList)
                .order("-sortIndex");
        if(saleStatus != null && !saleStatus.equals(ConstantUtil.SALE_STATE_ALL)){
            skuEntityQuery.filter("saleState", saleStatus);
        }
        return skuEntityQuery.count();
    }

    @Override
    public boolean save(SKUEntity skuEntity) {
        if(skuEntity==null || StringUtils.isBlank(skuEntity.getId())){
            return false;
        }
        dataStore.save(skuEntity);
        return true;
    }

    @Override
    public SKUEntity getSKUByCommon(SKUEntity skuEntity) {
        if(skuEntity == null){
            return null;
        }
        Query<SKUEntity> skuEntityQuery = dataStore.createQuery(SKUEntity.class);
        if(StringUtils.isNotBlank(skuEntity.getId())){
            skuEntityQuery.filter("_id", skuEntity.getId());
        }
        if(skuEntity.getSaleState() != null ){
            skuEntityQuery.filter("saleState", skuEntity.getSaleState());
        }
        if(StringUtils.isNotBlank(skuEntity.getShopId())){
            skuEntityQuery.filter("shopId", skuEntity.getShopId());
        }
        if(StringUtils.isNotBlank(skuEntity.getInterpreterId())){
            skuEntityQuery.filter("interpreterId", skuEntity.getInterpreterId());
        }
        if(StringUtils.isNotBlank(skuEntity.getSpuCode())){
            skuEntityQuery.filter("spuCode", skuEntity.getSpuCode());
        }
        if(StringUtils.isNotBlank(skuEntity.getSkuCode())){
            skuEntityQuery.filter("skuCode", skuEntity.getSkuCode());
        }
        if(StringUtils.isNotBlank(skuEntity.getSpuName())){
            skuEntityQuery.filter("spuName", skuEntity.getSpuName());
        }
        if(StringUtils.isNotBlank(skuEntity.getSpecifications())){
            skuEntityQuery.filter("specifications", skuEntity.getSpecifications());
        }
        return skuEntityQuery.get();
    }

    @Override
    public boolean update(SKUEntity skuEntity) {
        if(skuEntity==null || StringUtils.isBlank(skuEntity.getId())){
            return false;
        }
        Query<SKUEntity> skuEntityQuery = dataStore.createQuery(SKUEntity.class).filter("_id", skuEntity.getId());
        UpdateOperations<SKUEntity> ops = dataStore.createUpdateOperations(SKUEntity.class);

        ops.set("updatedAt", System.currentTimeMillis());
        if(CollectionUtils.isNotEmpty(skuEntity.getBookNotices())){
            ops.set("bookNotices", skuEntity.getBookNotices());
        }
        if(CollectionUtils.isNotEmpty(skuEntity.getTicketLabels())){
            ops.set("ticketLabels", skuEntity.getTicketLabels());
        }
        if(StringUtils.isNotBlank(skuEntity.getImageUrlOfSKU())){
            ops.set("imageUrlOfSKU", skuEntity.getImageUrlOfSKU());
        }
        if(StringUtils.isNotBlank(skuEntity.getInterpreterId())){
            ops.set("interpreterId", skuEntity.getInterpreterId());
        }
        if(StringUtils.isNotBlank(skuEntity.getSpecifications())){
            ops.set("specifications", skuEntity.getSpecifications());
        }
        if(StringUtils.isNotBlank(skuEntity.getSpuCode())){
            ops.set("spuCode", skuEntity.getSpuCode());
        }
        if(StringUtils.isNotBlank(skuEntity.getSpuName())){
            ops.set("spuName", skuEntity.getSpuName());
        }
        if(StringUtils.isNotBlank(skuEntity.getSkuCode())){
            ops.set("skuCode", skuEntity.getSkuCode());
        }
        if (skuEntity.getDiscountPrice() != null){
            ops.set("discountPrice", skuEntity.getDiscountPrice());
        }
        if (skuEntity.getMax2PermitPurchased() != null){
            ops.set("max2PermitPurchased", skuEntity.getMax2PermitPurchased());
        }
        if (skuEntity.getPrice() != null){
            ops.set("price", skuEntity.getPrice());
        }
        if (skuEntity.getPromotionState() != null){
            ops.set("promotionState", skuEntity.getPromotionState());
        }
        if (skuEntity.getSaleState() != null){
            ops.set("saleState", skuEntity.getSaleState());
        }
        if (skuEntity.getStocks() != null){
            ops.set("stocks", skuEntity.getStocks());
        }
        if(skuEntity.getPreSalePeriod() > 0){
            ops.set("preSalePeriod", skuEntity.getPreSalePeriod());
        }
        if(skuEntity.getSellPlatform() != null){
            ops.set("sellPlatform", skuEntity.getSellPlatform());
        }
        if(StringUtils.isNotBlank(skuEntity.getSellPlatformGoodsId())){
            ops.set("sellPlatformGoodsId", skuEntity.getSellPlatformGoodsId());
        }
        ops.set("sortIndex", skuEntity.getSortIndex());
        dataStore.update(skuEntityQuery, ops);
        return true;
    }

    @Override
    public List<SKUEntity> getSkuList(String shopId, List<String> spuCodeList, Integer saleState) {
        if(StringUtils.isBlank(shopId)){
            return new ArrayList<>();
        }
        Query<SKUEntity> skuEntityQuery = dataStore.createQuery(SKUEntity.class)
                .filter("shopId", shopId);

        if(CollectionUtils.isNotEmpty(spuCodeList)){
            skuEntityQuery.filter("spuCode in ", spuCodeList);
        }

        if(saleState != null){
            skuEntityQuery.filter("saleState", saleState);
        }

        return skuEntityQuery.asList();
    }

    @Override
    public boolean deleteByInterIdAndShopId(String InterId, String shopId) {
        if(StringUtils.isAnyBlank(InterId, shopId)){
            return false;
        }
        Query<SKUEntity> skuEntityQuery = dataStore.createQuery(SKUEntity.class)
                .filter("shopId", shopId)
                .filter("interpreterId", InterId);

        DeleteOptions deleteOptions = new DeleteOptions();
        deleteOptions.writeConcern(WriteConcern.ACKNOWLEDGED);
        WriteResult writeResult = dataStore.delete(skuEntityQuery, deleteOptions);
        return writeResult.getN()==1;
    }

    @Override
    public boolean deleteSkuByShopIdAndSkuIds(String shopId, List<String> skuIdList) {
        if(StringUtils.isBlank(shopId) || CollectionUtils.isEmpty(skuIdList)){
            return false;
        }

        Query<SKUEntity> skuEntityQuery = dataStore.createQuery(SKUEntity.class)
                .filter("shopId", shopId)
                .filter("_id in", skuIdList);

        WriteResult writeResult = dataStore.delete(skuEntityQuery, new DeleteOptions().writeConcern(WriteConcern.ACKNOWLEDGED));
        return writeResult.getN() > 0;
    }

    @Override
    public boolean updateSkuSaleStateByShopIdAndSkuIds(String shopId, List<String> skuIdList, Integer saleState) {
        
        if(StringUtils.isBlank(shopId) || CollectionUtils.isEmpty(skuIdList) || saleState==null){
            return false;
        }
        int saleStateInt = saleState.intValue();

        if(saleStateInt==ConstantUtil.SALE_STATE_OFF || saleStateInt==ConstantUtil.SALE_STATE_ON){
            Query<SKUEntity> skuEntityQuery = dataStore.createQuery(SKUEntity.class)
                    .filter("shopId", shopId)
                    .filter("_id in ", skuIdList);

            UpdateOperations<SKUEntity> ops = dataStore.createUpdateOperations(SKUEntity.class);

            ops.set("updatedAt", System.currentTimeMillis());
            ops.set("saleState", saleState);
            dataStore.update(skuEntityQuery, ops);
            return true;
        }

        return false;
    }
}
